package com.haoze.common.utils;

import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Map;

/**
 * @Author: Chenchao
 * @CreateTime: 2020-11-25 09:50
 */
@Component
public class CommonUtils {

    public void computeAge(Map<String, Object> map) {
        if (map.get("birthDay") != null && map.get("inDatetime") != null) {
            // 计算年龄
            Calendar c1 = Calendar.getInstance();
            c1.setTime(DateUtil.stringToDate(map.get("birthDay").toString()));
            Calendar c2 = Calendar.getInstance();
            c2.setTime(DateUtil.stringToDate(map.get("inDatetime").toString()));

            int[] times = DateUtil.getTimeIntervalArray(c2, c1);
            int years = times[0];
            int months = times[1];
            int days = times[2];
            int hours = times[3];
            int minutes = times[4];
            if (years >= 3) {
                map.put("age", years + "岁");
            } else if (years >= 1) {
                map.put("age", years + "岁" + (months == 0 ? "" : months + "月"));
            } else if (months >= 1) {
                map.put("age", months + "月" + (days == 0 ? "" : days + "天"));
            } else if (days >= 1) {
                map.put("age", days + "天");
            } else if (hours >= 1) {
                map.put("age", hours + "小时" + (minutes == 0 ? "" : minutes + "分钟"));
            } else if (minutes >= 0) {
                map.put("age", minutes + "分钟");
            } else {
                map.put("age", (years == 0 ? "" : years + "岁") + (months == 0 ? "" : months + "月") + (days == 0 ? "" : days + "天") + (hours == 0 ? "" : hours + "小时") + (minutes == 0 ? "" : minutes + "分钟"));
            }
        } else { // 当出生日期或者入院日期无效则采用下面策略计算时间
            if (map.get("ageDay") == null) {
                map.put("age", (map.get("ageYear") == null ? "" : map.get("ageYear") + "岁") + (map.get("ageMonth") == null ? "" : map.get("ageMonth") + "月"));
            } else {
                if (map.get("minutes") == null) {
                    map.put("age", (map.get("ageYear") == null ? "" : map.get("ageYear") + "岁") + (map.get("ageMonth") == null ? "" : map.get("ageMonth") + "月") + (map.get("ageDay") == null ? "" : map.get("ageDay") + "天"));
                } else {
                    int days = Integer.parseInt(map.get("minutes").toString()) / 60 / 24;
                    int hour = Integer.parseInt(map.get("minutes").toString()) / 60 % 24;
                    map.put("age", (days == 0 ? (hour == 0 ? "" : hour + "小时") : days + "天"));
                }
            }
        }
    }

}
